package com.glx.test.service.Impl;

import com.glx.test.dao.UserMapper;
import com.glx.test.pojo.User;
import com.glx.test.pojo.UserInfos;
import com.glx.test.response.LoginResponse;
import com.glx.test.response.RegisterResponse;
import com.glx.test.response.RegisterUserInfosResponse;
import com.glx.test.response.UserInfosResponse;
import com.glx.test.service.UserService;
import com.glx.test.utils.JwtUtils;
import com.glx.test.utils.Md5Utils;
import com.glx.test.utils.UserIdGenerator;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RegisterResponse registerResponse;

    @Value("${NginxFiles}")
    private String NginxFiles;

    @Value("${LocalFiles}")
    private String LocalFiles;

    private final String  HeadPictureFolder="HeadPicture";

    @Override
    public RegisterResponse register(User user) {
        // 对密码进行md5加密
        String md5Password = Md5Utils.md5Password(user.getUser_password());
        Long user_id = UserIdGenerator.generateUserId();
        user.setUser_createtime(LocalDateTime.now());
        user.setUser_id(user_id);
        user.setUser_password(md5Password);
        int i = userMapper.registerUser(user);
        if (i == 1){
            registerResponse.setResult("success");
            registerResponse.setMessage("注册成功");
            registerResponse.setUser_id(user_id);
            return registerResponse;
        }else{
            registerResponse.setResult("fail");
            registerResponse.setMessage("注册失败");
            return registerResponse;
        }
    }

    @Override
    public RegisterUserInfosResponse registerUserInfos(MultipartHttpServletRequest request) {
        // 获取上传的文件
        MultipartFile file = request.getFile("file");

        // 获取用户信息
        UserInfos userInfos = new UserInfos(
                Long.valueOf(request.getParameter("user_id")),
                request.getParameter("user_name"),
                LocalDate.parse(request.getParameter("user_birth")),
                request.getParameter("user_sex"),
                request.getParameter("user_introduction"),
                null
        );
        System.out.println("Received user info: " + userInfos);

        // 使用 LocalFiles 配置项创建文件保存目录
        Path path = Paths.get(LocalFiles, HeadPictureFolder);
        System.out.println("目标文件夹路径: " + path);  // 打印文件夹路径以调试

        // 检查并创建目录
        if (!path.toFile().exists()) {
            System.out.println("目录不存在，尝试创建: " + path);
            boolean dirsCreated = path.toFile().mkdirs();  // 创建目录
            if (dirsCreated) {
                System.out.println("目录创建成功: " + path);
            } else {
                System.out.println("目录创建失败: " + path);
            }
        } else {
            System.out.println("目录已存在: " + path);
        }

        // 生成文件保存的名称并保存文件
//        String fileName = userInfos.getUser_id() + ".jpg";  // 假设文件是图片，可以根据需要修改
        //添加随机数在文件后
        String fileName=userInfos.getUser_id()+"_" + System.currentTimeMillis() + ".jpg";
        userInfos.setUser_headpicture_url(NginxFiles + "HeadPicture/" + fileName);  // 设置头像 URL

        try {
            // 保存文件到本地磁盘
            file.transferTo(path.resolve(fileName));
            System.out.println("文件已保存: " + path.resolve(fileName));
        } catch (IOException e) {
            System.out.println("文件保存失败: " + e.getMessage());
            e.printStackTrace();
            RegisterUserInfosResponse registerUserInfosResponse = new RegisterUserInfosResponse();
            registerUserInfosResponse.setResult("fail");
            registerUserInfosResponse.setMessage("注册用户信息失败");
            return registerUserInfosResponse;
        }

        // 保存用户信息到数据库
        int i = userMapper.RegisterUserInfo(userInfos);
        RegisterUserInfosResponse registerUserInfosResponse = new RegisterUserInfosResponse();
        if (i == 1) {
            registerUserInfosResponse.setResult("success");
            registerUserInfosResponse.setMessage("注册用户信息成功");
        } else {
            registerUserInfosResponse.setResult("fail");
            registerUserInfosResponse.setMessage("注册用户信息失败");
        }

        return registerUserInfosResponse;
    }

    @Override
    public LoginResponse login(String account, String password) {
        User user = userMapper.getUserByUserAccount(account);

        if (user == null){
            return new LoginResponse("fail", "账号或密码错误", null, null);
        }
        if (Md5Utils.md5Password(password).equals(user.getUser_password())){
            LoginResponse loginResponse = new LoginResponse();
            loginResponse.setResult("success");
            loginResponse.setMessage("登录成功");
            Map<String, String> map = new HashMap<>();
            map.put("user_id", String.valueOf(user.getUser_id()));
            // 生成token
            loginResponse.setToken(JwtUtils.getToken(map));
            loginResponse.setUser_id(user.getUser_id());
            return loginResponse;
        }else{
            return new LoginResponse("fail", "登录失败", null, null);
        }
    }

    @Override
    public UserInfosResponse getUserInfos(Long user_id,String token) {
        try {
            JwtUtils.verify(token);
        } catch (Exception e) {
            return new UserInfosResponse("fail", "Token验证失败", null);
        }
        if (userMapper.getUserInfos(user_id) == null){
            return new UserInfosResponse("fail", "用户信息不存在", null);
        }
        return new UserInfosResponse("success", "获取用户信息成功", userMapper.getUserInfos(user_id));
    }

    @Override
    public UserInfosResponse updateUserInfos(UserInfos userInfos, String token) {
        try {
            JwtUtils.verify(token);
        } catch (Exception e) {
            return new UserInfosResponse("fail", "Token验证失败", null);
        }
        if (userMapper.updateUserInfos(userInfos) == 1){
            return new UserInfosResponse("success", "更新用户信息成功", userMapper.getUserInfos(userInfos.getUser_id()));
        }else{
            return new UserInfosResponse("fail", "更新用户信息失败", null);
        }
    }

    @Override
    public UserInfosResponse updateUserInfos_headpicture_url(MultipartHttpServletRequest request) {
        String token = request.getParameter("token");
        try {
            JwtUtils.verify(token);
        } catch (Exception e) {
            return new UserInfosResponse("fail", "Token验证失败", null);
        }

        Long user_id = Long.valueOf(request.getParameter("user_id"));
        MultipartFile file = request.getFile("file");

        if (file == null || file.isEmpty()) {
            return new UserInfosResponse("fail", "文件为空", null);
        }

        String fileName = user_id + "_" + System.currentTimeMillis() + ".jpg";
        Path path = Paths.get(LocalFiles, HeadPictureFolder);
        String user_headpicture_url = NginxFiles + "HeadPicture/" + fileName;

        try {
            // 查询用户信息以获取旧头像 URL
            UserInfos userInfos = userMapper.getUserInfos(user_id);
            if (userInfos != null) {
                String oldUserHeadpictureUrl = userInfos.getUser_headpicture_url();

                if (oldUserHeadpictureUrl != null && oldUserHeadpictureUrl.contains("/files/")) {
                    // 截取本地路径
                    String oldFilePath = oldUserHeadpictureUrl.substring(
                            oldUserHeadpictureUrl.indexOf("/files/") + 7
                    );
                    File oldFile = new File(LocalFiles + oldFilePath);
                    if (oldFile.exists()) {
                        boolean deleted = oldFile.delete();
                        if (!deleted) {
                            System.out.println("旧头像删除失败: " + oldFile.getAbsolutePath());
                        } else {
                            System.out.println("旧头像已删除: " + oldFile.getAbsolutePath());
                        }
                    }
                }
            }

            // 保存新头像到本地磁盘
            file.transferTo(path.resolve(fileName));
            System.out.println("新头像已保存: " + path.resolve(fileName));
        } catch (IOException e) {
            System.out.println("文件保存失败: " + e.getMessage());
            e.printStackTrace();
            return new UserInfosResponse("fail", "更新用户头像失败", null);
        }

        // 更新数据库中的头像 URL
        if (userMapper.updateUser_headpicture_url(user_id, user_headpicture_url) == 1) {
            UserInfos updatedUserInfos = userMapper.getUserInfos(user_id);
            return new UserInfosResponse("success", "更新用户头像成功", updatedUserInfos);
        } else {
            return new UserInfosResponse("fail", "更新用户头像失败", null);
        }
    }

    @Override
    public UserInfosResponse updateUser_password(Long user_id,String user_account,String OldPassword,
                                                 String user_password,String token) {
        try {
            JwtUtils.verify(token);
        }catch (Exception e){
            return new UserInfosResponse("fail","token验证失败",null);
        }
        User OldUserInfos = userMapper.getUserByUserAccount(user_account);
        if (!Md5Utils.md5Password(OldPassword).equals(OldUserInfos.getUser_password())){
            return new UserInfosResponse("fail","旧密码错误",null);
        }

        int i = userMapper.updateUser_password(user_id, Md5Utils.md5Password(user_password));
        if (i == 1){
            UserInfos userInfos = userMapper.getUserInfos(user_id);
            return new UserInfosResponse("success","更新用户密码成功",userInfos);
        }else{
            return new UserInfosResponse("fail","更新用户密码失败",null);
        }
    }


}
